package com.ruoyi.common.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.ServiceException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.OSSObject;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.uuid.UUID;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;


@Slf4j
@Data
@Component
public class AliyunOss {

    @Value("${oss.endpoint}")
    private String endpoint;
    @Value("${oss.pubendpoint}")
    private String pubendpoint;
    @Value("${oss.ak}")
    private String ak;
    @Value("${oss.sk}")
    private String sk;
    @Value("${oss.bucketname}")
    private String bucketName;

//    private DefaultCredentialProvider credentialsProvider;
//    private OSS                       ossClient;
//
//
//    @PostConstruct
//    public void init() {
//        credentialsProvider = CredentialsProviderFactory.newDefaultCredentialProvider(ak, sk);
//        ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
//    }

    public String upload(MultipartFile file) {
        DefaultCredentialProvider credentialsProvider;
        OSS                       ossClient;
        credentialsProvider = CredentialsProviderFactory.newDefaultCredentialProvider(ak, sk);
        ossClient           = new OSSClientBuilder().build(endpoint, credentialsProvider);
        // 文件名
        String fileName = file.getOriginalFilename();
        // 文件大小
        long fileSize = file.getSize();
        // 文件类型
        String contentType = file.getContentType();
        // 文件上传
        try {
            String          uuid            = UUID.fastUUID().toString();
            String          ext             = FileUploadUtils.getExtension(file);
            String          newFileName     = uuid + "." + ext;
            ossClient.putObject(bucketName, newFileName, file.getInputStream());
            log.info("文件上传成功，文件名：{}，文件大小：{}，文件类型：{}", fileName, fileSize, contentType);
            String url = "https://" + bucketName + "." + pubendpoint + "/" + newFileName;
            log.info("***** 文件上传成功，文件地址：{}", url);
            return url;

        } catch (Exception e) {
            log.error("***** 文件上传失败*****", e);
            throw new ServiceException("文件上传失败");
        } finally {
            if (null != ossClient) {
                ossClient.shutdown();
            }
        }

    }


    public String uploadByLocalFile(String fileLinkPath) {

        log.info("fileLinkPath = {}", fileLinkPath);
        DefaultCredentialProvider credentialsProvider;
        OSS                       ossClient;
        credentialsProvider = CredentialsProviderFactory.newDefaultCredentialProvider(ak, sk);
        ossClient           = new OSSClientBuilder().build(endpoint, credentialsProvider);
        // 文件名
//        String fileName = file.getOriginalFilename();
//        // 文件大小
//        long fileSize = file.getSize();
//        // 文件类型
//        String contentType = file.getContentType();
        // 文件上传
        try {
            String          uuid            = UUID.fastUUID().toString();
            String          ext             = getFileExtension(fileLinkPath);
            String          newFileName     = uuid + "." + "mp3";
            // 使用OkHttp从URL下载文件
            OkHttpClient okHttpClient = new OkHttpClient();
            Request  request  = new Request.Builder().url(fileLinkPath).build();
            Response response = okHttpClient.newCall(request).execute();
            if (!response.isSuccessful()) {
                throw new IOException("Failed to download file: " + response);
            }
            assert response.body() != null;
            InputStream inputStream = response.body().byteStream();
            ossClient.putObject(bucketName, newFileName, inputStream);
//            log.info("文件上传成功，文件名：{}，文件大小：{}，文件类型：{}", fileName, fileSize, contentType);
            String url = "https://" + bucketName + "." + pubendpoint + "/" + newFileName;
            log.info("***** 文件上传成功，文件地址：{}", url);
            return url;

        } catch (Exception e) {
            log.error("***** 文件上传失败*****", e);
            throw new ServiceException("文件上传失败");
        } finally {
            if (null != ossClient) {
                ossClient.shutdown();
            }
        }
    }

    // 辅助方法，用于从文件URL中提取文件扩展名
    private String getFileExtension(String fileUrl) {
        // 根据文件URL提取文件扩展名的逻辑
        // 这只是一个示例，您需要根据实际URL格式来实现这个方法
        int index = fileUrl.lastIndexOf('.');
        return fileUrl.substring(index + 1);
    }

    public void download(String filename, HttpServletResponse response) throws IOException {
        DefaultCredentialProvider credentialsProvider;
        OSS                       ossClient;
        credentialsProvider = CredentialsProviderFactory.newDefaultCredentialProvider(ak, sk);
        ossClient           = new OSSClientBuilder().build(endpoint, credentialsProvider);
        log.info("***** 文件下载开始，文件名：{}", filename);
        OSSObject object = ossClient.getObject(bucketName, filename);
        if (object != null && object.getObjectContent() != null) {
            log.info("***** 文件下载成功，文件名：{}", filename);
            InputStream is = object.getObjectContent();
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            FileUploadUtils.transTo(is, response.getOutputStream());
        }

    }

    public void delete() {

    }

    public void list() {
    }
}
